package com.jh.fcsm.service.sys.impl;

import com.jh.fcsm.beans.sys.vo.LoginUser;
import com.jh.fcsm.beans.sys.vo.Token;
import com.jh.fcsm.constant.RedisConstant;
import com.jh.fcsm.service.sys.TokenService;
import com.jh.fcsm.util.security.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * token存到redis的实现类<br>
 * 普通token，uuid
 */
@Service
public class TokenServiceImpl implements TokenService {

    /**
     * token过期秒数
     */
    @Value("${token.expire.seconds}")
    private Integer expireSeconds;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String getToken(HttpServletRequest request) {
        // 头部的Authorization值以Bearer开头
        String auth = request.getHeader("Authorization");
        if (auth != null && !"".equals(auth)) {
            if (auth.startsWith(OAuth2AccessToken.BEARER_TYPE)) {
                auth = auth.replace(OAuth2AccessToken.BEARER_TYPE, "");
                auth=JwtUtils.getUserKey(auth);
                return auth.trim();
            }
        }
        auth = request.getParameter("access_token");
        auth=JwtUtils.getUserKey(auth);
        return auth;
    }

    @Override
    public Token saveToken(LoginUser loginUser) {
        String token = UUID.randomUUID().toString();

        loginUser.setToken(token);
        cacheLoginUser(loginUser);
        return new Token(token, loginUser.getLoginTime());
    }

    private void cacheLoginUser(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireSeconds * 1000);
        redisTemplate.boundValueOps(getTokenKey(loginUser.getToken())).set(loginUser, expireSeconds, TimeUnit.SECONDS);
    }

    /**
     * 更新缓存的用户信息
     */
    @Override
    public void refresh(LoginUser loginUser) {
        cacheLoginUser(loginUser);
    }

    @Override
    public Object getLoginUser(String token) {
        return redisTemplate.boundValueOps(getTokenKey(token)).get();
    }

    @Override
    public boolean deleteToken(String token) {
        String key = getTokenKey(token);
        Object loginUser = redisTemplate.opsForValue().get(key);
        if (loginUser != null) {
            redisTemplate.delete(key);
            return true;
        }

        return false;
    }

    private String getTokenKey(String token) {
        return RedisConstant.SYS_REDIS + "tokens:" + token;
    }

}
